import { ratedApi, moviesApi, moreApi } from "@/api/home";

// 首页模块
const indexModule = {
  namespaced: true,
  state: {
    // 最受欢迎列表
    ratedList: [],
    // 电影列表
    moviesList: [],
    count: 0,
    ids: [],
    startIndex: 0,
  },

  mutations: {
    getRatedData(state, payload) {
      state.ratedList = payload.result;
    },
    getMoviesList(state, payload) {
      state.moviesList = payload.result;
      state.count = payload.count;
      state.startIndex = payload.result.length;
      state.ids = payload.ids;
    },
    getmore2(state, payload) {
      state.moviesList = [...state.moviesList, ...payload.result];
      state.startIndex += 6;
    },
  },
  actions: {
    // 请求最受欢迎列表
    asyncGetData({ commit }) {
      return new Promise((resolve) => {
        ratedApi().then((res) => {
          commit("getRatedData", res);
          resolve();
        });
      });
    },
    asyncGetMoviesList({ commit }) {
      return new Promise((resolve) => {
        moviesApi().then((res) => {
          commit("getMoviesList", res);
          resolve();
        });
      });
    },
    getMore({ commit, state }) {
      return new Promise((resolve) => {
        const ids = state.ids.slice(state.startIndex, state.startIndex + 6);
        moreApi({ ids: ids.join(",") }).then((res) => {
          commit("getmore2", res);
          resolve(state.moviesList.length >= state.count);
        });
      });
    },
  },
};

export default indexModule;
